#include "stdafx.h"
#include "Service.h"
#include "Task.h"
#include "EventUtil.h"

//////////////////////////////////////////////////////////////////////////

Service::Service()
{

}

Service::~Service()
{

}

void Service::Reset()
{
	OnReset();
}

EventChannel* Service::CreateSysChannel()
{
	ASSERT(g_EventService);
	return g_EventService->CreateSysChannel();
}

void Service::MakeSysTask(Task* task)
{
	ASSERT(g_TaskService);
	g_TaskService->MakeSystemTask(task);
}

//////////////////////////////////////////////////////////////////////////

EventService::EventService()
{

}

EventService::~EventService()
{
	std::for_each(m_Channels.begin(), m_Channels.end(), DeleteFunc());
	EventInfo::DestoryStaticData();
}

void EventService::RemoveHandler(IEventHandler* handler)
{
	for (ChannelSet::iterator itr = m_Channels.begin(), end = m_Channels.end(); itr != end; ++itr)
	{
		(*itr)->RemoveHandler(handler);
	}
}

EventChannel* EventService::CreateChannel()
{
	EventChannel* channel = new EventChannel();
	m_Channels.insert(channel);

	return channel;
}

EventChannel* EventService::CreateSysChannel()
{
	EventChannel* c = CreateChannel();
	c->m_IsSystemChannel = true;

	return c;
}

void EventService::RemoveChannel(EventChannel* c)
{
	ChannelSet::iterator itr = m_Channels.find(c);
	ASSERT(itr != m_Channels.end());

	if (itr != m_Channels.end())
	{
		m_Channels.erase(itr);
		delete c;
	}
}

struct RemoveNonSysChannelFn
{
	EventService* service;
	RemoveNonSysChannelFn(EventService* service) : service(service) {}

	void operator() (EventChannel* c)
	{
		if (!c->IsSystemChannel())
			service->RemoveChannel(c);
	}
};

void EventService::OnReset()
{
	SafeIterate(m_Channels, RemoveNonSysChannelFn(this));
}

struct StepTickFun
{
	void operator() (EventChannel* channel) {channel->GetScheduler()->StepTick();}
};

void EventService::StepTick()
{
	SafeIterate(m_Channels, StepTickFun());
}

//////////////////////////////////////////////////////////////////////////

TaskService::TaskService()
{
}

TaskService::~TaskService()
{
	std::for_each(m_TaskList.begin(), m_TaskList.end(), DeleteFunc());
}

struct StopNonSysTaskFn
{
	void operator () (Task* task)
	{
		if (!task->IsSystemTask())
			task->Stop();
	}
};

void TaskService::BroadCast( Event* evt )
{
	SafeIterate(m_TaskList, std::bind2nd(std::mem_fun(&Task::Send), evt));
}

void TaskService::OnReset()
{
	SafeIterate(m_TaskList,StopNonSysTaskFn());
}

void TaskService::OnActivate(Task* task)
{
	m_TaskList.push_back(task);
}

void TaskService::OnDeactivate(Task* task)
{
	TaskList::iterator itr = std::find(m_TaskList.begin(), m_TaskList.end(), task);
	if (itr != m_TaskList.end())
	{
		m_TaskList.erase(itr);
	}
}

void TaskService::MakeSystemTask(Task* task)
{
	task->m_IsSystemTask = true;
}